﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OracleClient;
using System.Data;

namespace ConfigurationManager.DataAccess
{
    public class Product : BaseResourceAccess
    {
        public Product()
            : base()
        {
        }

        public List<Model.Product> Retrieve()
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT COD_PRDT, NOME_PRDT, DESC_PRDT ");
            sql.Append("FROM TFWDPRDT_GDOR_PROS");

            OracleCommand command = this.OracleConnection.CreateCommand();
            command.CommandText = sql.ToString();
            command.CommandType = System.Data.CommandType.Text;

            List<Model.Product> ret = new List<ConfigurationManager.Model.Product>();

            try
            {
                this.OracleConnection.Open();

                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Model.Product product = new Model.Product();
                        product.Id = reader.GetInt32(0);
                        product.Name = reader.GetString(1);
                        product.Description = reader.GetString(2);

                        ret.Add(product);
                    }
                }
                return ret;
            }
            catch
            {
                throw;
            }
            finally
            {
                this.OracleConnection.Close();
            }
        }

        public Model.Product Retrieve(int id)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT COD_PRDT, NOME_PRDT, DESC_PRDT ");
            sql.Append("FROM TFWDPRDT_GDOR_PROS ");
            sql.Append("WHERE COD_PRDT = :COD_PRDT ");
            sql.Append("ORDER BY COD_PRDT ");

            OracleCommand command = this.OracleConnection.CreateCommand();
            command.CommandText = sql.ToString();
            command.CommandType = System.Data.CommandType.Text;
            command.Parameters.Add(new OracleParameter("COD_PRDT", id));

            List<Model.Product> ret = new List<ConfigurationManager.Model.Product>();

            try
            {
                this.OracleConnection.Open();

                using (IDataReader reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        Model.Product product = new Model.Product();
                        product.Id = reader.GetInt32(0);
                        product.Name = reader.GetString(1);
                        product.Description = reader.GetString(2);
                        return product;
                    }
                    else
                        return null;
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                this.OracleConnection.Close();
            }
        }

        public bool VerifyProductNameIntegrity(int id, string name)
        {
            OracleCommand command = this.OracleConnection.CreateCommand();

            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT 1 ");
            sql.Append("FROM TFWDPRDT_GDOR_PROS ");
            sql.Append("WHERE NOME_PRDT = :NOME_PRDT ");

            if (id != 0)
            {
                sql.Append("AND COD_PRDT <> :COD_PRDT ");
                command.Parameters.Add(new OracleParameter("COD_PRDT", id));
            }

            command.CommandText = sql.ToString();
            command.CommandType = System.Data.CommandType.Text;
            command.Parameters.Add(new OracleParameter("NOME_PRDT", name));

            try
            {
                this.OracleConnection.Open();
                object ret = command.ExecuteScalar();
                return !(ret == null || ret == DBNull.Value);
            }
            catch
            {
                throw;
            }
            finally
            {
                this.OracleConnection.Close();
            }
        }


        public void Save(Model.Product product)
        {
            StringBuilder sql = new StringBuilder();
            OracleCommand lockCommand = null;
            OracleTransaction trans = null;
            try
            {
                this.OracleConnection.Open();
                trans = this.OracleConnection.BeginTransaction();

                //lock da tabela para evitar problemas na geracao do id
                lockCommand = this.OracleConnection.CreateCommand();
                lockCommand.Transaction = trans;
                lockCommand.CommandText = "SELECT 1 FROM TFWDPRDT_GDOR_PROS FOR UPDATE";
                lockCommand.CommandType = System.Data.CommandType.Text;
                lockCommand.ExecuteNonQuery();

                if (product.Id > 0)
                {
                    sql.Append("UPDATE TFWDPRDT_GDOR_PROS ");
                    sql.Append("SET ");
                    sql.Append("NOME_PRDT=:NOME_PRDT, ");
                    sql.Append("DESC_PRDT=:DESC_PRDT ");
                    sql.Append("WHERE COD_PRDT=:COD_PRDT ");

                }
                else
                {
                    product.Id = this.GetNextId(trans);
                    sql.Append("INSERT INTO TFWDPRDT_GDOR_PROS ");
                    sql.Append("(COD_PRDT, NOME_PRDT, DESC_PRDT) ");
                    sql.Append("VALUES (:COD_PRDT, :NOME_PRDT, :DESC_PRDT) ");
                }

                OracleCommand command = this.OracleConnection.CreateCommand();
                command.Transaction = trans;
                command.CommandText = sql.ToString();
                command.CommandType = System.Data.CommandType.Text;
                command.Parameters.Add(new OracleParameter("COD_PRDT", product.Id));
                command.Parameters.Add(new OracleParameter("NOME_PRDT", product.Name));
                command.Parameters.Add(new OracleParameter("DESC_PRDT", product.Description));

                if (command.ExecuteNonQuery() == 0)
                    throw new Exception(string.Format("Não foi possível atualizar o produto. Id:{0} Name:{1}", product.Id, product.Name));

                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();

                throw;
            }
            finally
            {
                this.OracleConnection.Close();
            }
        }

        public void Delete(int id)
        {
            StringBuilder sql = new StringBuilder();
            OracleTransaction trans = null;
            try
            {
                this.OracleConnection.Open();
                sql.Append("DELETE FROM TFWDPRDT_GDOR_PROS ");
                sql.Append("WHERE COD_PRDT=:COD_PRDT ");

                OracleCommand command = this.OracleConnection.CreateCommand();
                command.Transaction = trans;
                command.CommandText = sql.ToString();
                command.CommandType = System.Data.CommandType.Text;
                command.Parameters.Add(new OracleParameter("COD_PRDT", id));

                if (command.ExecuteNonQuery() == 0)
                    throw new Exception(string.Format("Não foi possível excluir o produto. Id:{0}", id));

            }
            catch
            {
                throw;
            }
            finally
            {
                this.OracleConnection.Close();
            }
        }

        private int GetNextId(OracleTransaction trans)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT MAX(COD_PRDT) FROM TFWDPRDT_GDOR_PROS");

            OracleCommand command = this.OracleConnection.CreateCommand();
            command.Transaction = trans;
            command.CommandType = System.Data.CommandType.Text;
            command.CommandText = sql.ToString();

            try
            {
                object ret = command.ExecuteScalar();

                if (ret is DBNull)
                    return 1;
                else
                    return Convert.ToInt32(command.ExecuteScalar()) + 1;
            }
            catch
            {
                throw;
            }
        }

        public Model.Product RetrieveByName(string productName)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT COD_PRDT, NOME_PRDT, DESC_PRDT ");
            sql.Append("FROM TFWDPRDT_GDOR_PROS ");
            sql.Append("WHERE UPPER(NOME_PRDT) = UPPER(:NOME_PRDT) ");
            sql.Append("ORDER BY COD_PRDT ");

            OracleCommand command = this.OracleConnection.CreateCommand();
            command.CommandText = sql.ToString();
            command.CommandType = System.Data.CommandType.Text;
            command.Parameters.Add(new OracleParameter("NOME_PRDT", productName));

            List<Model.Product> ret = new List<ConfigurationManager.Model.Product>();

            try
            {
                this.OracleConnection.Open();

                using (IDataReader reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        Model.Product product = new Model.Product();
                        product.Id = reader.GetInt32(0);
                        product.Name = reader.GetString(1);
                        product.Description = reader.GetString(2);
                        return product;
                    }
                    else
                        return null;
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                this.OracleConnection.Close();
            }
        }
    }
}
